package com.zxt.controller;

import com.google.code.kaptcha.Producer;
import com.wf.captcha.ArithmeticCaptcha;
import com.zxt.annotation.RepeatSubmit;
import com.zxt.bean.AjaxResult;
import com.zxt.constant.CacheConstants;
import com.zxt.constant.Constants;
import com.zxt.redis.RedisCache;
import com.zxt.utils.sign.Base64;
import com.zxt.utils.uuid.IdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author zxt
 */
@RestController
@Api(tags = "验证码")
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @RepeatSubmit
    @GetMapping("/captchaImage")
    @ApiOperation(value = "生成验证码", notes = "生成验证码")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        Map<String, String> data = new HashMap<>();
        String uuid = IdUtils.simpleUUID();
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        // 获取运算的公式
        captcha.getArithmeticString();
        // 获取运算的结果
        String text = captcha.text();
        data.put("uuid", uuid);
        data.put("img", captcha.toBase64());
        // 验证码结果放到缓存中，30分钟有效

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        redisCache.setCacheObject(verifyKey, text, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        AjaxResult ajax = AjaxResult.success();
        //验证码开关
        boolean captchaEnabled = Boolean.TRUE;
        ajax.put("captchaEnabled", captchaEnabled);
        ajax.put("uuid", uuid);
        ajax.put("img", captcha.toBase64());
        return ajax;
    }
}
